import os
import random
from PIL import Image,ImageDraw,ImageFont,ImageFilter


def check_code(font_file="HanYiYanKaiW-2.ttf",width=120,height=30,str_length=4,font_size=28):
    """
    生成随机图片验证码
    :params:width【图片宽度】,height【图片高度】,str_length【文字个数】,font_size【int,字体大小】,
            font_file【string,字体文件路径】,
    :return:
    """
    code = []
    # 创建图片
    img = Image.new(mode="RGB", size=(120, 30), color=(255, 255, 255))
    # 创建画笔
    draw = ImageDraw.Draw(img, mode="RGB")

    def random_str():
        """生成随机字母"""
        return chr(random.randint(65,90))

    def random_color():
        """生成随机颜色"""
        return random.randint(0, 255), random.randint(10, 255), random.randint(64, 255)

    # 写特殊字体的文字
    font = ImageFont.truetype(font_file,font_size)
    for i in range(str_length):
        char = random_str()
        code.append(char)
        h = random.randint(0,4)
        draw.text([i * width / str_length,h],char,random_color(),font=font)

    # 画干扰点
    for j in range(40):
        draw.point((random.randint(0,width),random.randint(0,height)),fill=random_color())

    # 画干扰圆圈
    for k in range(40):
        x = random.randint(0,width)
        y = random.randint(0,height)
        draw.arc((x,y,x+4,y+4),0,90,fill=random_color())

    # 画干扰线
    for k in range(4):
        x1 = random.randint(0, width)
        y1 = random.randint(0, height)
        x2 = random.randint(0, width)
        y2 = random.randint(0, height)
        draw.line((x1,y1,x2,y2),fill=random_color())

    img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
    return img,''.join(code)


if __name__ == '__main__':
    img,code_str = check_code()
    print(code_str)

    # 保存图片
    # print(os.getcwd())
    os.chdir(r'G:\python\my_modules\Django\No_1\firstweb\static\img')
    with open('code.png', 'wb') as f:
        img.save(f, format='png')